#define _CRT_SECURE_NO_WARNINGS 1
class Solution {
public:
    int threeSumClosest(vector<int>& nums, int target) {

        sort(nums.begin(), nums.end());
        int ans = 1e9;
        for (int i = 0; i < nums.size(); i++) {
            int l = i + 1;
            int r = nums.size() - 1;

            while (l < r) {
                int sum = nums[i] + nums[l] + nums[r];
                if (abs(sum - target) < abs(target - ans)) {
                    ans = sum;
                }

                if (sum > target)r--;
                else if (sum < target)l++;
                else
                    return target;

            }
        }
        return ans;
    }
};